package com.yksj.healthtalk.ui.server;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import sfs2x.client.core.SFSEvent;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.yksj.healthtalk.adapter.DoctorAdapter;
import com.yksj.healthtalk.adapter.DoctorAdapter.onClickFriendAttentionListener;
import com.yksj.healthtalk.adapter.DoctorAdapter.onClickFriendHeadListener;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.entity.DoctorParameter;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonHttpResponseHandler;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.http.RequestParams;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.doctor.DoctorExactSearchActivity;
import com.yksj.healthtalk.ui.doctor.DoctorNavigationLisenter;
import com.yksj.healthtalk.ui.friend.DoctorMainActivity;
import com.yksj.healthtalk.ui.views.DoctorNavigationBar;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.JsonParseUtils;
import com.yksj.healthtalk.utils.PersonInfoUtil;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * 服务中心 医生服务列表(医疗类)
 * @author Administrator
 *
 */
public class ServerMedicalCenterDoctorList extends BaseFragmentActivity
		implements DoctorNavigationLisenter, OnRefreshListener2<ListView>,
		OnClickListener, onClickFriendHeadListener, OnItemClickListener, onClickFriendAttentionListener {

	private DoctorNavigationBar mDoctorNavigationBar;
	private PullToRefreshListView mPullToRefreshListView;
	private DoctorAdapter adapter;
	private ArrayList<CustomerInfoEntity> entities;
	private ListView mListView;
	private int size;
	private DoctorParameter parameter;
	String position = "";// pop position
	int clickBtnId = 0;// 导航id
	private String merchantid;
	private int mDepartmentCode;//科室的code
	BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (action.equals(MessagePushService.ACTION_COLLECT_FRIEND)) {
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(ServerMedicalCenterDoctorList.this, R.string.groupNewFail);
				} else if (result.equals("-1")) {
					ToastUtil.showShort(ServerMedicalCenterDoctorList.this,R.string.against__blacklist_operations);
				} else {
					FriendHttpUtil.requestAttentionTofriendsResult(ServerMedicalCenterDoctorList.this, cacheCustomerInfoEntity, appData);
					adapter.notifyDataSetChanged();
				}
			} else if (action.equals(MessagePushService.ACTION_MESSAGE)) {
				if (intent.hasExtra("senderId")) {
					adapter.notifyDataSetChanged();
				}
			}
		}
	};
	private AppData appData;
	private CustomerInfoEntity cacheCustomerInfoEntity;
	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.doctor_main_layout);
		merchantid = getIntent().getStringExtra("id");
		appData = HTalkApplication.getAppData();
		initWidget();
		initData();
	}

	
	@Override
	public void onStop() {
		unregisterReceiver(receiver);
		super.onStop();
	}

	@Override
	public void onStart() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(MessagePushService.ACTION_COLLECT_FRIEND);
		filter.addAction(SFSEvent.CONNECTION_LOST);
		filter.addAction(MessagePushService.ACTION_MESSAGE);
		registerReceiver(receiver, filter);
		super.onStart();
	}
	private RequestParams getParameterStr(int size, DoctorParameter parameter) {
		if (parameter == null) {
			parameter = new DoctorParameter(mDepartmentCode);
		}
		this.size = size;
		RequestParams params= new RequestParams();
		params.put("MERCHANTID", merchantid);
		params.put("PAGESIZE", size+"");
		params.put("PAGENUM", "20");
		params.put("PUBLICFLAG", "1");
		params.put("FLAG", "1");
		params.put("CLASSID", parameter.getDOCTOROFFICE()+"");
		params.put("CUSTOMERID", SmartFoxClient.getLoginUserId());
		params.put("AREA", parameter.getAREA()+"");
		params.put("doctorTitle", parameter.getDOCTORTITLE()+"");
		params.put("doctorHospital", parameter.getDOCTORHOSPITAL()+"");
		params.put("orderOnOff", parameter.getORDERONOFF()+"");
		params.put("serviceTypeId", parameter.getSERVICETYPEID()+"");
		params.put("officeFlag", parameter.getOfficeFlag()+"");
		params.put("MAIN_DOCTOR_OFFICE", parameter.getMAIN_DOCTOR_OFFICE()+"");
		return params;
	}


	private void initWidget() {
		initTitle();
		mDoctorNavigationBar = (DoctorNavigationBar) findViewById(R.id.doctor_navigationbar);
		mPullToRefreshListView = (PullToRefreshListView) findViewById(R.id.hall);
		mListView = mPullToRefreshListView.getRefreshableView();
		mListView.addFooterView(LayoutInflater.from(getApplicationContext())
				.inflate(R.layout.list_line_layout, null));

		titleTextV.setText("专家列表");
		titleRightBtn2.setVisibility(View.VISIBLE);
		titleRightBtn2.setBackgroundResource(R.drawable.icon_search_press);

		mDoctorNavigationBar.setDoctorNavigationLisenter(this);
		mPullToRefreshListView.setOnRefreshListener(this);
		titleRightBtn2.setOnClickListener(this);
		titleLeftBtn.setOnClickListener(this);
		mListView.setOnItemClickListener(this);

	}

	private void initData() {
		mDepartmentCode = Integer.valueOf(getIntent().getStringExtra("code"));
		entities = new ArrayList<CustomerInfoEntity>();
		adapter = new DoctorAdapter(getApplicationContext(), entities, false);
		adapter.setonClickFriendHeadListener(this);
		adapter.setonClickFriendAttentionListener(this);
		mListView.setAdapter(adapter);

		RequestParams params = getParameterStr(1, parameter);
		mPullToRefreshListView.setRefreshing();
		HttpRestClient.doHttpServerMedicalCenterDoctorList(params,new AsyncDoctorListHander(position, clickBtnId));
	}

	@Override
	public void OnSelectService(View v) {
		HttpRestClient.doHttpDoctorSelectService(new AsyncServiceHander(v));
	}

	class AsyncServiceHander extends JsonHttpResponseHandler {
		View v;
		public AsyncServiceHander(View v) {
			super(ServerMedicalCenterDoctorList.this);
			this.v = v;
		}
		@Override
		public void onSuccess(int statusCode, JSONArray response) {
			ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
			HashMap<String, String> map = new HashMap<String, String>();
			for (int i = 0; i < response.length(); i++) {
				try {
					map = new HashMap<String, String>();
					JSONObject object = response.getJSONObject(i);
					String service_type_id = "";
					String service_type = "";
					if (object.has("OFFICE_NAME")) {//科室
						 service_type_id = object
								.getString("OFFICE_CODE");
						 service_type = object.getString("OFFICE_NAME");
					}else {//服务类型
						service_type_id = object.getString("SERVICE_TYPE_ID");
						 service_type = object.getString("SERVICE_TYPE");
						 if (list.size() == 0) {
								map.put("SERVICE_TYPE_ID", "0");
								map.put("SERVICE_TYPE", "全部");
								list.add(map);
								map = new HashMap<String, String>();
						}
					}
					map.put("SERVICE_TYPE_ID", service_type_id);
					map.put("SERVICE_TYPE", service_type);
					list.add(map);
					if (v.getId() == 1) {
						mDoctorNavigationBar.choiceService(v, list);  
					} else if (v.getId() == 5) {
						mDoctorNavigationBar.choiceDcotorDepartments(v, list);
					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				super.onSuccess(statusCode, response);
			}
		}
	}

	// 医生列表请求
	class AsyncDoctorListHander extends ObjectHttpResponseHandler {

		public AsyncDoctorListHander(String position, int clickBtnId) {
			ServerMedicalCenterDoctorList.this.position = position;
			ServerMedicalCenterDoctorList.this.clickBtnId = clickBtnId;
		}

		@Override
		public Object onParseResponse(String content) {
			JSONObject object;
			try {
				object = new JSONObject(content);
				return JsonParseUtils.jsonfilter(object.getString("list"));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		@Override
		public void onSuccess(int statusCode, Object response) {
			if (size == 1) {
				entities.clear();
			}
			if (response != null && response instanceof ArrayList) {
				++size;
				entities.addAll((Collection<? extends CustomerInfoEntity>) response);
			} else if (response != null && response instanceof String) {
				ToastUtil.showShort(getApplicationContext(),response.toString());
			}

			adapter.notifyDataSetChanged();
			super.onSuccess(statusCode, response);
		}

		@Override
		public void onFinish() {
			// TODO Auto-generated method stub
			mPullToRefreshListView.onRefreshComplete();
			super.onFinish();
		}

		@Override
		public void onStart() {
			super.onStart();
		}

	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		HttpRestClient.doHttpServerMedicalCenterDoctorList(getParameterStr(1, parameter),
				new AsyncDoctorListHander(position, clickBtnId));

	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
		HttpRestClient.doHttpServerMedicalCenterDoctorList(getParameterStr(size, parameter),
				new AsyncDoctorListHander(position, clickBtnId));
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.title_right2:
			Intent intent = new Intent(getApplicationContext(),DoctorExactSearchActivity.class);
			intent.putExtra("merchantid",merchantid);
			startActivity(intent);
		default:
			break;
		}
	}

	@Override
	public void onClickFriendHead(CustomerInfoEntity entity, int positon) {
		PersonInfoUtil.choiceActivity(entity.getId(),this ,String.valueOf(entity.getRoldid()));
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (0 < arg2 && arg2 <= entities.size()) {
			onClickFriendHead(entities.get(arg2-1), arg2-1); 
		}
	}



	@Override
	public void OnHttpGetDoctorListForNavigation(
			HashMap<Integer, String> allSelect,
			HashMap<Integer, String> hashMap, String position, int clickBtnId) {
		parameter = new DoctorParameter(mDepartmentCode);
		for (Map.Entry<Integer, String> e : allSelect.entrySet()) {
			switch (e.getKey()) {
			case 1:
				parameter.setSERVICETYPEID(Integer.valueOf(hashMap.get(1)));
				break;
			case 2:
				parameter.setORDERONOFF(Integer.valueOf(hashMap.get(2)));
				break;

			case 3:// 城市
				parameter.setAREA(Integer.valueOf(hashMap.get(3)));
				break;
			case 4:// 医院
				parameter.setDOCTORHOSPITAL(hashMap.get(4));
				break;
			case 5:// 科室
				parameter.setDOCTOROFFICE(Integer.valueOf(hashMap.get(5)));
				parameter.setOfficeFlag(1);//小科室
				break;
			case 6:// 职称
				parameter.setDOCTORTITLE(Integer.valueOf(hashMap.get(6)));
				break;
			}
		}
		mPullToRefreshListView.setRefreshing();
		HttpRestClient.doHttpServerMedicalCenterDoctorList(getParameterStr(1, parameter),
				new AsyncDoctorListHander(position, clickBtnId));
	}

	@Override
	public void OnDcotorDepartments(View view) {
		HttpRestClient.doHttpMinDcotorDepartments(merchantid,mDepartmentCode+"",new AsyncServiceHander(view));
	}

	@Override
	public void onClickFriendAttention(int attentioned,CustomerInfoEntity entity, int positon) {
		cacheCustomerInfoEntity = FriendHttpUtil.requestAttentionTofriends(this, null, entity);
	}
}
